package com.adms.service;

import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.adms.domain.Grid;
import com.adms.domain.GridMapper;
import com.adms.domain.Message;
import com.adms.domain.MessageMapper;
import com.adms.domain.Reform;
import com.adms.domain.ReformDelay;
import com.adms.domain.ReformDelayMapper;
import com.adms.domain.ReformExample;
import com.adms.domain.ReformExample.Criteria;
import com.adms.domain.ReformExecute;
import com.adms.domain.ReformExecuteMapper;
import com.adms.domain.ReformMapper;
import com.adms.domain.ReformReply;
import com.adms.domain.ReformReplyExample;
import com.adms.domain.ReformReplyMapper;
import com.adms.domain.ReformSign;
import com.adms.domain.ReformSignMapper;
import com.adms.domain.ReformView;
import com.adms.domain.ReformViewMapper;
import com.adms.domain.Site;
import com.adms.domain.SiteGridUser;
import com.adms.domain.SiteGridUserMapper;
import com.adms.domain.SiteHandleUser;
import com.adms.domain.SiteHandleUserMapper;
import com.adms.domain.SiteLegalUserMapper;
import com.adms.domain.SiteMapper;
import com.adms.domain.User;
import com.adms.domain.UserMapper;
import com.adms.util.AdmsConfig;
import com.adms.util.AliMessageUtil;
import com.adms.util.ShiroUtil;
import com.adms.websocket.WebSocketServer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;

@Transactional
@Service
public class ReformService {

	@Autowired
	private ReformMapper reformMapper;
	@Autowired
	private ReformReplyMapper reformReplyMapper;
	@Autowired
	private ReformDelayMapper reformDelayMapper;
	@Autowired
	private MessageMapper messageMapper;
	@Autowired
	private WebSocketServer webSocketServer;
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private ReformExecuteMapper reformExecuteMapper;
	@Autowired
	private SiteMapper siteMapper;
	@Autowired
	private ReformViewMapper reformViewMapper;
	@Autowired
	private GridMapper gridMapper;
	@Autowired
	private ObjectMapper objectMapper;
	@Autowired
	private SiteGridUserMapper siteGridUserMapper;
	@Autowired
	private SiteHandleUserMapper siteHandleUserMapper;
	@Autowired
	private SiteLegalUserMapper siteLegalUserMapper;
	@Autowired
	private ReformSignMapper reformSignMapper;

	public Reform getByReformId(Integer reformId) {
		return reformMapper.selectByPrimaryKey(reformId);
	}

	public Map<String, Object> getByReformIdWithCustom(Integer reformId) {
		User loginUser = ShiroUtil.getUser();
		Integer loginUserId = loginUser.getUserId();
		String loginRole = loginUser.getRole();
		Map<String, Object> withCustom = reformMapper.selectByPrimaryKeyWithProcedure(reformId);
		boolean isSelf = false;
		boolean canReply = false;
		boolean canTransfer = false;
		boolean canDefer = false;
		boolean canHandle = false;
		boolean canConfirm = false;
		if (loginRole.equals(AdmsConfig.ROLE_ENVDEPARTMENT) || loginRole.equals(AdmsConfig.ROLE_ENVLEADER)) {
			if (loginUserId.equals(withCustom.get("userId"))) {
				isSelf = true;
			}
			if (loginUserId.equals(withCustom.get("gridUserId"))) {
				ReformReplyExample ex = new ReformReplyExample();
				ex.or().andReformIdEqualTo(reformId).andIsGridRepliedEqualTo(true);
				List<ReformReply> selectByExample = reformReplyMapper.selectByExample(ex);
				if (selectByExample.isEmpty() || selectByExample.get(0).getGridAuditState() == 2) {
					canReply = true;
				}
				SiteGridUser siteGridUser = siteGridUserMapper.selectByPrimaryKey((Integer) withCustom.get("siteId"),
						loginUserId);
				if (siteGridUser != null && siteGridUser.getIsDefault()) {
					canTransfer = true;
				}
			}
		} else {
			if (loginUserId.equals(withCustom.get("gridUserId"))) {
				ReformReplyExample ex = new ReformReplyExample();
				ex.or().andReformIdEqualTo(reformId).andIsGridRepliedEqualTo(true);
				List<ReformReply> selectByExample = reformReplyMapper.selectByExample(ex);
				if (selectByExample.isEmpty() || selectByExample.get(0).getGridAuditState() == 2) {
					canReply = true;
				}
				SiteGridUser siteGridUser = siteGridUserMapper.selectByPrimaryKey((Integer) withCustom.get("siteId"),
						loginUserId);
				if (siteGridUser != null && siteGridUser.getIsDefault()) {
					canTransfer = true;
				}
			} else if (loginUserId.equals(withCustom.get("handleUserId"))) {
				ReformReplyExample ex = new ReformReplyExample();
				ex.or().andReformIdEqualTo(reformId).andIsHandleRepliedEqualTo(true);
				List<ReformReply> selectByExample = reformReplyMapper.selectByExample(ex);
				if (selectByExample.isEmpty() || selectByExample.get(0).getHandleAuditState() == 2) {
					canReply = true;
				}
				SiteHandleUser siteHandleUser = siteHandleUserMapper
						.selectByPrimaryKey((Integer) withCustom.get("siteId"), loginUserId);
				if (siteHandleUser != null && siteHandleUser.getIsDefault()) {
					canTransfer = true;
				}
				canDefer = (boolean) withCustom.get("canDefer");
				canHandle = (boolean) withCustom.get("canHandle");
				canConfirm = (boolean) withCustom.get("canConfirm");
			}
		}
		withCustom.put("isSelf", isSelf);
		withCustom.put("canReply", canReply);
		withCustom.put("canTransfer", canTransfer);
		withCustom.put("canDefer", canDefer);
		withCustom.put("canHandle", canHandle);
		withCustom.put("canConfirm", canConfirm);
		return withCustom;
	}

	public PageInfo<Reform> list(Reform reform, Boolean isSelf, String timeField, Date start, Date end, String key,
			String orderByClause, Integer pageNum, Integer pageSize, Integer navigatePages) {

		ReformExample ex = constructExample(reform, isSelf, timeField, start, end, orderByClause);

		PageHelper.startPage(pageNum, pageSize);
		List<Reform> reforms;
		if (StringUtil.isEmpty(key)) {
			reforms = reformMapper.selectByExample(ex);
		} else {
			reforms = reformMapper.selectByExampleWithKey(ex, "%" + key + "%");
		}
		return new PageInfo<>(reforms, navigatePages);
	}

	public List<Reform> listRelative(Integer reformId, Integer type, Integer state, Integer signType) {
		return reformMapper.listRelative(reformId, type, state, signType);
	}
	
	public Map<String,Object> count(){
		Map<String,Object> result = new HashMap<>();
		result = reformMapper.count();
		return result;
	}

	private ReformExample constructExample(Reform reform, Boolean isSelf, String timeField, Date start, Date end,
			String orderByClause) {
		ReformExample ex = new ReformExample();
		Criteria or = ex.or();
		// 判断角色若为网格员,交办人,负责人,则设置限定条件
		User loginUser = ShiroUtil.getUser();
		Integer loginUserId = loginUser.getUserId();
		String loginRole = loginUser.getRole();
		List<Integer> siteIds = new ArrayList<>();
		if (loginRole.equals(AdmsConfig.ROLE_GRIDOPERATOR)) {
			siteIds = siteGridUserMapper.selectSiteIdsByGridUserId(loginUserId);
		} else if (loginRole.equals(AdmsConfig.ROLE_HANDLEPERSON)) {
			siteIds = siteHandleUserMapper.selectSiteIdsByHandleUserId(loginUserId);
		} else if (loginRole.equals(AdmsConfig.ROLE_LEGALPERSON)) {
			siteIds = siteLegalUserMapper.selectSiteIdsByLegalUserId(loginUserId);
		}
		if (!siteIds.isEmpty()) {
			or.andSiteIdIn(siteIds);
		}
		if (reform != null) {
			Integer siteId = reform.getSiteId();
			Integer userId = reform.getUserId();
			Integer state = reform.getState();
			Integer refReformId = reform.getRefReformId();
			Boolean hasReminded = reform.getHasReminded();
			Boolean isContinued = reform.getIsContinued();
			Boolean canDefer = reform.getCanDefer();
			Boolean canHandle = reform.getCanHandle();
			Boolean isTimeOver = reform.getIsTimeOver();
			Boolean isLeading = reform.getIsLeading();
			Integer gridUserId = reform.getGridUserId();
			Integer handleUserId = reform.getHandleUserId();
			Integer legalUserId = reform.getLegalUserId();
			Integer parentReformId = reform.getParentReformId();
			Integer type = reform.getType();
			Integer signType = reform.getSignType();
			if (siteId != null) {
				or.andSiteIdEqualTo(siteId);
			}
			if (userId != null) {
				or.andUserIdEqualTo(userId);
			}
			if (state != null) {
				or.andStateEqualTo(state);
			}
			if (refReformId != null) {
				or.andRefReformIdEqualTo(refReformId);
			}
			if (hasReminded != null) {
				or.andHasRemindedEqualTo(hasReminded);
			}
			if (isContinued != null) {
				or.andIsContinuedEqualTo(isContinued);
			}
			if (canDefer != null) {
				or.andCanDeferEqualTo(canDefer);
			}
			if (canHandle != null) {
				or.andCanHandleEqualTo(canHandle);
			}
			if (isTimeOver != null) {
				or.andIsTimeOverEqualTo(isTimeOver);
			}
			if (isLeading != null) {
				or.andIsLeadingEqualTo(isLeading);
			}
			if (gridUserId != null) {
				or.andGridUserIdEqualTo(gridUserId);
			}
			if (handleUserId != null) {
				or.andHandleUserIdEqualTo(handleUserId);
			}
			if (legalUserId != null) {
				or.andLegalUserIdEqualTo(legalUserId);
			}
			if (parentReformId != null) {
				or.andParentReformIdEqualTo(parentReformId);
			}
			if (type != null) {
				or.andTypeEqualTo(type);
			}
			if (signType != null) {
				or.andSignTypeEqualTo(signType);
			}
		}
		if (StringUtil.isNotEmpty(timeField)) {
			if (timeField.equals("publishTime")) {
				if (start != null) {
					if (end != null) {
						or.andPublishTimeBetween(start, end);
					} else {
						or.andPublishTimeGreaterThanOrEqualTo(start);
					}
				} else {
					if (end != null) {
						or.andPublishTimeLessThanOrEqualTo(end);
					}
				}
			}
			if (timeField.equals("endTime")) {
				if (start != null) {
					if (end != null) {
						or.andEndTimeBetween(start, end);
					} else {
						or.andEndTimeGreaterThanOrEqualTo(start);
					}
				} else {
					if (end != null) {
						or.andEndTimeLessThanOrEqualTo(end);
					}
				}
			}
			if (timeField.equals("maxEndTime")) {
				if (start != null) {
					if (end != null) {
						or.andMaxEndTimeBetween(start, end);
					} else {
						or.andMaxEndTimeGreaterThanOrEqualTo(start);
					}
				} else {
					if (end != null) {
						or.andMaxEndTimeLessThanOrEqualTo(end);
					}
				}
			}
			if (timeField.equals("finishTime")) {
				if (start != null) {
					if (end != null) {
						or.andFinishTimeBetween(start, end);
					} else {
						or.andFinishTimeGreaterThanOrEqualTo(start);
					}
				} else {
					if (end != null) {
						or.andFinishTimeLessThanOrEqualTo(end);
					}
				}
			}
		}
		if (isSelf != null && isSelf) {
			or.andUserIdEqualTo(loginUserId);
		}
		if (StringUtil.isNotEmpty(orderByClause)) {
			ex.setOrderByClause(orderByClause);
		} else {
			ex.setOrderByClause("reform.publish_time desc");
		}
		return ex;
	}

	public boolean publish(Reform reform) {
		// 校验工地
		Integer siteId = reform.getSiteId();
		if (siteId == null) {
			throw new RuntimeException("工地id不能为空");
		}
		Site site = siteMapper.selectByPrimaryKey(siteId);
		if (site == null) {
			throw new RuntimeException("工地不存在");
		}
		// 绑定工地名称
		reform.setSiteName(site.getName());
		// 校验网格
		Integer gridId = site.getGridId();
		if (gridId == null) {
			throw new RuntimeException("此工地未被纳入网格");
		}
		Grid grid = gridMapper.selectByPrimaryKey(gridId);
		if (grid == null) {
			throw new RuntimeException("网格不存在");
		}
		User loginUser = ShiroUtil.getUser();
		reform.setUserId(loginUser.getUserId());
		reform.setUsername(loginUser.getUsername());
		// 设置截止时间和最大截止时间
		Calendar calendar = Calendar.getInstance();
		if (reform.getEndTime() == null) {
			// 默认设置24小时时限
			calendar.add(Calendar.HOUR_OF_DAY, 24);
			reform.setEndTime(calendar.getTime());
			calendar.add(Calendar.HOUR_OF_DAY, 24 * 6);
		} else {
			calendar.add(Calendar.HOUR_OF_DAY, 24 * 7);
		}
		reform.setMaxEndTime(calendar.getTime());
		reform.setPublishTime(new Date());
		// 关联用户
		Set<User> relativeUsers = new HashSet<>();
		User defaultGridUser = userMapper.selectDefaultGridUserBySiteId(siteId);
		User defaultHandleUser = userMapper.selectDefaultHandleUserBySiteId(siteId);
		User defaultLegalUser = userMapper.selectDefaultLegalUserBySiteId(siteId);
		if(defaultGridUser != null) {
			reform.setGridUserId(defaultGridUser.getUserId());
			relativeUsers.add(defaultGridUser);
		}
		if(defaultHandleUser != null) {
			reform.setHandleUserId(defaultHandleUser.getUserId());
			relativeUsers.add(defaultHandleUser);
		}
		if(defaultLegalUser != null) {
			reform.setLegalUserId(defaultLegalUser.getUserId());
			relativeUsers.add(defaultLegalUser);
		}
		reformMapper.insertSelective(reform);
		// 新增站内信
		Integer reformId = reform.getReformId();
		Message message;
		String title = reform.getTitle();
		DateFormat dateFormat = objectMapper.getDateFormat();
		Integer userId;
		for (User relativeUser : relativeUsers) {
			userId = relativeUser.getUserId();
			message = new Message();
			message.setReformId(reformId);
			message.setUserId(userId);
			message.setTitle(title);
			message.setType(AdmsConfig.MESSAGE_TYPE_PUBLISHREFORM);
			messageMapper.insertSelective(message);
			// 发送webSocket消息
			webSocketServer.sendMessage(userId, message);
			// 发送短信
			AliMessageUtil.sendMessageForPublishReform(relativeUser.getPhone(), reform.getSiteName(),
					dateFormat.format(reform.getPublishTime()), dateFormat.format(reform.getEndTime()));
		}
		return true;
	}

	public boolean continuePublish(Reform reform) {
		Integer refReformId = reform.getRefReformId();
		// 更新引用整改单为持续整改
		Reform r = new Reform();
		r.setReformId(refReformId);
		r.setIsContinued(true);
		reformMapper.updateByPrimaryKeySelective(r);
		// 修改数据关联原始reformId然后调用publish接口发布新的整改单
		reform.setType(1);
		return publish(reform);
	}

	public boolean respond(Integer reformId, String content, String signature) {
		User loginUser = ShiroUtil.getUser();
		Integer loginUserId = loginUser.getUserId();
		// 获取目标整改单
		Reform reform = reformMapper.selectByPrimaryKey(reformId);
		if (loginUserId.equals(reform.getGridUserId())) {
			gridRespond(reform,reformId, content, signature);
		} else if (loginUserId.equals(reform.getHandleUserId())) {
			handleRespond(reform,reformId, content, signature);
		}
		return true;
	}

	private void gridRespond(Reform reform,Integer reformId, String content, String signature) {
		User loginUser = ShiroUtil.getUser();
		// 根据reformId获取关联回复单
		ReformReplyExample ex = new ReformReplyExample();
		ex.or().andReformIdEqualTo(reformId);
		List<ReformReply> reformReplys = reformReplyMapper.selectByExample(ex);
		// 没有对应回复单则新增回复单
		ReformReply reformReply;
		if (reformReplys.isEmpty()) {
			reformReply = new ReformReply();
			reformReply.setReformId(reformId);
			reformReply.setIsGridReplied(true);
			reformReply.setGridContent(content);
			reformReply.setGridReplyTime(new Date());
			reformReply.setGridSignature(signature);
			reformReply.setGridUserId(loginUser.getUserId());
			reformReply.setGridUsername(loginUser.getUsername());
			reformReplyMapper.insertSelective(reformReply);
			//修改整改单状态为已回复
			reform.setState(1);
			reformMapper.updateByPrimaryKey(reform);
			// 新增站内信
			Integer envUserId = reform.getUserId();
			Message message = new Message();
			message.setUserId(envUserId);
			message.setReformId(reformId);
			message.setReplyId(reformReply.getReplyId());
			message.setTitle(reform.getTitle());
			message.setType(AdmsConfig.MESSAGE_TYPE_GRIDRESPONSEREFORM);
			messageMapper.insertSelective(message);
			// 发送webSocket消息
			webSocketServer.sendMessage(envUserId, message);
		} else {
			reformReply = reformReplys.get(0);
			if (!reformReply.getIsGridReplied()) {
				reformReply.setIsGridReplied(true);
				reformReply.setGridContent(content);
				reformReply.setGridReplyTime(new Date());
				reformReply.setGridSignature(signature);
				reformReply.setGridUserId(loginUser.getUserId());
				reformReply.setGridUsername(loginUser.getUsername());
				reformReply.setGridAuditState(0);
				reformReplyMapper.updateByPrimaryKeySelective(reformReply);
				// 新增站内信
				Integer envUserId = reform.getUserId();
				Message message = new Message();
				message.setUserId(envUserId);
				message.setReformId(reformId);
				message.setReplyId(reformReply.getReplyId());
				message.setTitle(reform.getTitle());
				message.setType(AdmsConfig.MESSAGE_TYPE_GRIDRESPONSEREFORM);
				messageMapper.insertSelective(message);
				// 发送webSocket消息
				webSocketServer.sendMessage(envUserId, message);
			}
		}
	}

	private void handleRespond(Reform reform,Integer reformId, String content, String signature) {
		User loginUser = ShiroUtil.getUser();
		// 根据reformId获取关联回复单
		ReformReplyExample ex = new ReformReplyExample();
		ex.or().andReformIdEqualTo(reformId);
		List<ReformReply> reformReplys = reformReplyMapper.selectByExample(ex);
		// 没有对应回复单则新增回复单
		ReformReply reformReply;
		if (reformReplys.isEmpty()) {
			reformReply = new ReformReply();
			reformReply.setReformId(reformId);
			reformReply.setIsHandleReplied(true);
			reformReply.setHandleContent(content);
			reformReply.setHandleReplyTime(new Date());
			reformReply.setHandleSignature(signature);
			reformReply.setHandleUserId(loginUser.getUserId());
			reformReply.setHandleUsername(loginUser.getUsername());
			reformReplyMapper.insertSelective(reformReply);
			//修改整改单状态为已回复
			reform.setState(1);
			reformMapper.updateByPrimaryKey(reform);
			// 新增站内信
			Integer envUserId = reform.getUserId();
			Message message = new Message();
			message.setUserId(envUserId);
			message.setReformId(reformId);
			message.setReplyId(reformReply.getReplyId());
			message.setTitle(reform.getTitle());
			message.setType(AdmsConfig.MESSAGE_TYPE_HANDLERESPONSEREFORM);
			messageMapper.insertSelective(message);
			// 发送webSocket消息
			webSocketServer.sendMessage(envUserId, message);
		} else {
			reformReply = reformReplys.get(0);
			if (!reformReply.getIsHandleReplied()) {
				reformReply.setIsHandleReplied(true);
				reformReply.setHandleContent(content);
				reformReply.setHandleReplyTime(new Date());
				reformReply.setHandleSignature(signature);
				reformReply.setHandleUserId(loginUser.getUserId());
				reformReply.setHandleUsername(loginUser.getUsername());
				reformReply.setHandleAuditState(0);
				reformReplyMapper.updateByPrimaryKeySelective(reformReply);
				// 新增站内信
				Integer envUserId = reform.getUserId();
				Message message = new Message();
				message.setUserId(envUserId);
				message.setReformId(reformId);
				message.setReplyId(reformReply.getReplyId());
				message.setTitle(reform.getTitle());
				message.setType(AdmsConfig.MESSAGE_TYPE_HANDLERESPONSEREFORM);
				messageMapper.insertSelective(message);
				// 发送webSocket消息
				webSocketServer.sendMessage(envUserId, message);
			}
		}
	}

	public boolean defer(Integer reformId, String content, String images, Date delayTime) {
		// 获取目标整改单
		Reform reform = reformMapper.selectByPrimaryKey(reformId);
		// 新增整改延期单
		ReformDelay reformDelay = new ReformDelay();
		reformDelay.setReformId(reformId);
		reformDelay.setContent(content);
		reformDelay.setImages(images);
		reformDelay.setDelayTime(delayTime);
		reformDelayMapper.insertSelective(reformDelay);
		// 更新整改单可申请延期为false
		reform.setCanDefer(false);
		reformMapper.updateByPrimaryKey(reform);
		// 新增站内信
		// 获取关联的网格员id
		Integer gridUserId = reform.getGridUserId();
		Message message = new Message();
		message.setUserId(gridUserId);
		message.setReformId(reformId);
		message.setDelayId(reformDelay.getDelayId());
		message.setTitle(reform.getTitle());
		message.setType(AdmsConfig.MESSAGE_TYPE_DEFERREFORM);
		messageMapper.insertSelective(message);
		// 发送webSocket消息
		webSocketServer.sendMessage(gridUserId, message);
		return true;
	}

	public boolean handle(Integer reformId, String content, String images) {
		// 获取目标整改单
		Reform reform = reformMapper.selectByPrimaryKey(reformId);
		// 新增整改执行单
		ReformExecute reformExecute = new ReformExecute();
		reformExecute.setReformId(reformId);
		reformExecute.setContent(content);
		reformExecute.setImages(images);
		reformExecuteMapper.insertSelective(reformExecute);
		// 更新整改单可执行为false
		reform.setCanHandle(false);
		reformMapper.updateByPrimaryKey(reform);
		// 新增站内信
		// 获取关联的网格员id
		Integer gridUserId = reform.getGridUserId();
		Message message = new Message();
		message.setUserId(gridUserId);
		message.setReformId(reformId);
		message.setExecuteId(reformExecute.getExecuteId());
		message.setTitle(reform.getTitle());
		message.setType(AdmsConfig.MESSAGE_TYPE_HANDLEREFORM);
		messageMapper.insertSelective(message);
		// 发送webSocket消息
		webSocketServer.sendMessage(gridUserId, message);
		return true;
	}

	public boolean inspect(Integer reformId, String content, String images) {
		// 新增整改视察单
		ReformView reformView = new ReformView();
		reformView.setReformId(reformId);
		reformView.setContent(content);
		reformView.setImages(images);
		reformViewMapper.insertSelective(reformView);
		return true;
	}

	public boolean confirm(Integer reformId, String images) {
		Reform reform = reformMapper.selectByPrimaryKey(reformId);
		// 新增整改确认单
		ReformSign reformSign = new ReformSign();
		reformSign.setReformId(reformId);
		reformSign.setImages(images);
		reformSignMapper.insertSelective(reformSign);
		// 更新整改单状态为有整改执行,并且可执行为false
		reform.setCanConfirm(false);
		reformMapper.updateByPrimaryKey(reform);
		// 新增站内信
		// 获取关联的环安科id
		Integer envUserId = reform.getUserId();
		Message message = new Message();
		message.setUserId(envUserId);
		message.setReformId(reformId);
		message.setSignId(reformSign.getSignId());
		message.setTitle(reform.getTitle());
		message.setType(AdmsConfig.MESSAGE_TYPE_CONFIRMREFORM);
		messageMapper.insertSelective(message);
		// 发送webSocket消息
		webSocketServer.sendMessage(envUserId, message);
		return true;
	}

	public boolean update(Reform reform) {
		reformMapper.updateByPrimaryKeySelective(reform);
		return true;
	}

	public boolean delete(int[] reformIds) {
		if (reformIds != null) {
			int length = reformIds.length;
			if (length > 0) {
				if (length == 1) {
					reformMapper.deleteByPrimaryKey(reformIds[0]);
				} else {
					reformMapper.deleteBatch(reformIds);
				}
			}
		}
		return true;
	}

	@Scheduled(fixedDelay = 60000)
	public void remind() {
		// 更新超时整改
		reformMapper.updateTimeOver();
		// 获取待提醒整改单
		List<Reform> forRemindReforms = reformMapper.selectForRemindReforms();
		if (!forRemindReforms.isEmpty()) {
			DateFormat dateFormat = objectMapper.getDateFormat();
			Integer reformId;
			String title;
			Message message;
			List<Integer> relativeUserIds;
			User relativeUser;
			for (Reform forRemindReform : forRemindReforms) {
				reformId = forRemindReform.getReformId();
				title = forRemindReform.getTitle();
				relativeUserIds = new ArrayList<>();
				relativeUserIds.add(forRemindReform.getLegalUserId());
				relativeUserIds.add(forRemindReform.getHandleUserId());
				relativeUserIds.add(forRemindReform.getGridUserId());
				for (Integer relativeUserId : relativeUserIds) {
					// 新增站内信
					message = new Message();
					message.setReformId(reformId);
					message.setTitle(title);
					message.setType(AdmsConfig.MESSAGE_TYPE_REMINDEFORM);
					message.setUserId(relativeUserId);
					messageMapper.insertSelective(message);
					// 发送websocket
					webSocketServer.sendMessage(relativeUserId, message);
					// 发送短信通知
					relativeUser = userMapper.selectByPrimaryKey(relativeUserId);
					if (relativeUser != null) {
						AliMessageUtil.sendMessageForRemindReform(relativeUser.getPhone(),
								forRemindReform.getSiteName(), dateFormat.format(forRemindReform.getEndTime()));
					}
				}
				// 更新整改单为已提醒
				forRemindReform.setHasReminded(true);
				reformMapper.updateByPrimaryKey(forRemindReform);
			}
		}
	}

	public boolean transferTo(Integer reformId, Integer userId) {
		User loginUser = ShiroUtil.getUser();
		Integer loginUserId = loginUser.getUserId();
		Reform reform = reformMapper.selectByPrimaryKey(reformId);
		if(loginUserId.equals(reform.getGridUserId())) {
			reform.setGridUserId(userId);
		}else if(loginUserId.equals(reform.getHandleUserId())) {
			reform.setHandleUserId(userId);
		}else {
			return true;
		}
		reformMapper.updateByPrimaryKey(reform);
		//新增站内信
		Message message = new Message();
		message.setUserId(userId);
		message.setReformId(reformId);
		message.setTitle(reform.getTitle());
		message.setType(AdmsConfig.MESSAGE_TYPE_TRANSFERTO);
		messageMapper.insertSelective(message);
		webSocketServer.sendMessage(userId, message);
		return true;
	}

}
